//
//  Permit.swift
//  casdon_swiftUI
//
//  Created by ww on 2025/5/16.
//

//  PermissionManager.swift
import Foundation
import CoreBluetooth
import CoreLocation
import Network
import Combine
import NetworkExtension

import SystemConfiguration.CaptiveNetwork
import CoreLocation

enum NetworkType: String {
    case wifi
    case cellular
    case unavailable
}

final class PermissionManager: NSObject, ObservableObject {
    
    static let shared = PermissionManager()
   

    @Published private(set) var isBluetoothPoweredOn: Bool = false
    @Published private(set) var isNetworkReachable: Bool = false
    @Published private(set) var isUsingCellular: Bool = false
    @Published private(set) var bluetoothStatus: CBManagerAuthorization = .notDetermined
    @Published private(set) var locationStatus: CLAuthorizationStatus = .notDetermined
    @Published private(set) var isLocalNetworkAuthorized: Bool = false
    @Published private(set) var currentNetworkType: NetworkType = .unavailable
    @Published private(set) var isInternetAvailable: Bool = false

    private let locationManager = CLLocationManager()
    private let bluetoothManager: CBCentralManager
    private let networkMonitor = NWPathMonitor()

    private override init() {
        bluetoothManager = CBCentralManager(delegate: nil, queue: nil, options: [CBCentralManagerOptionShowPowerAlertKey: true])
        super.init()
        self.locationManager.delegate = self
        self.bluetoothManager.delegate = self
        startMonitoring()
    }
    
    // 是否连接了互联网，网络可以访问
    func testInternetConnection() {
        checkInternetAccess { [weak self] isAvailable in
            self?.isInternetAvailable = isAvailable
        }
    }

    func requestLocationPermission() {
        locationManager.requestWhenInUseAuthorization()
    }

    func refreshBluetoothStatus() {
        // 重新触发授权检查
        _ = CBCentralManager(delegate: nil, queue: nil)
    }
    
    // 是否为5Gwifi
    func ispro5GWifi() -> Bool {
        // 伪代码示例
        let ssid = self.getWiFiSSID() ?? ""
        let mightNotBe5G = (ssid.contains("5.0") || ssid.contains("5G") || ssid.contains("_5G"))
        return mightNotBe5G

    }
    // 获取当前wifi 名ssid
    ///注意：你需要请求定位权限（CLLocationManager().requestWhenInUseAuthorization()），否则无法获取。
    func getWiFiSSID() -> String? {
        if let interfaces = CNCopySupportedInterfaces() as NSArray? {
            for interface in interfaces {
                if let interfaceInfo = CNCopyCurrentNetworkInfo(interface as! CFString) as NSDictionary? {
                    return interfaceInfo[kCNNetworkInfoKeySSID as String] as? String
                }
            }
        }
        return nil
    }

    func openAppSettings() {
        guard let url = URL(string: UIApplication.openSettingsURLString) else { return }
        if UIApplication.shared.canOpenURL(url) {
            UIApplication.shared.open(url, options: [:], completionHandler: nil)
        }
    }

    private func startMonitoring() {
        monitorNetwork()
        checkLocalNetworkPermission()
        _ = bluetoothManager // 触发授权状态读取
        locationManager.requestWhenInUseAuthorization()
    }

    // 网络功能是否打开 wifi or 蜂窝网络
    private func monitorNetwork() {
        networkMonitor.pathUpdateHandler = { [weak self] path in
            DispatchQueue.main.async {
                self?.isNetworkReachable = path.status == .satisfied
                self?.isUsingCellular = path.isExpensive

                if path.status == .satisfied {
                    if path.usesInterfaceType(.wifi) {
                        self?.currentNetworkType = .wifi
                    } else if path.usesInterfaceType(.cellular) {
                        self?.currentNetworkType = .cellular
                    } else {
                        self?.currentNetworkType = .unavailable
                    }
                } else {
                    self?.currentNetworkType = .unavailable
                }
            }
        }
        networkMonitor.start(queue: DispatchQueue.global(qos: .background))
    }


    private func checkLocalNetworkPermission() {
        // iOS 14+ 会自动弹窗，无 API 检查，只能间接判断
        // 触发 Bonjour 浏览尝试（局域网使用）
        let browser = NetServiceBrowser()
        browser.searchForServices(ofType: "_http._tcp.", inDomain: "local.")
        DispatchQueue.main.asyncAfter(deadline: .now() + 3.0) {
            browser.stop()
            self.isLocalNetworkAuthorized = true // 默认认为用户授权
        }
    }
    
    // 是否连接了互联网，网络可以访问
    private  func checkInternetAccess(completion: @escaping (Bool) -> Void) {
        guard let url = URL(string: "https://www.apple.com/library/test/success.html") else {
            completion(false)
            return
        }

        var request = URLRequest(url: url)
        request.timeoutInterval = 5

        URLSession.shared.dataTask(with: request) { _, response, error in
            DispatchQueue.main.async {
                if let httpResponse = response as? HTTPURLResponse, httpResponse.statusCode == 200 {
                    completion(true)
                } else {
                    completion(false)
                }
            }
        }.resume()
    }
}

// MARK: - CLLocationManagerDelegate

extension PermissionManager: CLLocationManagerDelegate {
    func locationManagerDidChangeAuthorization(_ manager: CLLocationManager) {
        locationStatus = manager.authorizationStatus
    }
}

// MARK: - CBCentralManagerDelegate

extension PermissionManager: CBCentralManagerDelegate {
    func centralManagerDidUpdateState(_ central: CBCentralManager) {
        bluetoothStatus = CBCentralManager.authorization
        isBluetoothPoweredOn = central.state == .poweredOn
    }
}

